package org.road0329.dlt698.axdr;

import org.road0329.dlt698.ReverseByteArrayInputStream;
import org.road0329.dlt698.ReverseByteArrayOutputStream;
import org.road0329.dlt698.asn1.axdr.AxdrType;

import java.io.IOException;

public class GetRecord extends AxdrType {
    private byte[] dataCode = null;
    private OAD oad = null;
    private RSD rsd = null;
    private RCSD rcsd = null;

    public GetRecord() {
    }

    public void setDataCode(byte[] dataCode) {
        this.dataCode = dataCode;
    }

    public void setAll(OAD oad, RSD rsd, RCSD rcsd) {
        this.oad = oad;
        this.rsd = rsd;
        this.rcsd = rcsd;
    }

    public void setOad(OAD oad) {
        this.oad = oad;
    }

    public void setRsd(RSD rsd) {
        this.rsd = rsd;
    }

    public void setRcsd(RCSD rcsd) {
        this.rcsd = rcsd;
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) throws Exception {
        int codeLength = 0;
        this.oad = new OAD();
        codeLength += this.oad.decode(input);
        this.rsd = new RSD();
        codeLength += this.rsd.decode(input);
        this.rcsd = new RCSD();
        codeLength += this.rcsd.decode(input);
        return codeLength;
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) throws Exception {
        int codeLength;
        if (this.dataCode != null) {
            codeLength = this.dataCode.length;
            for (int i = this.dataCode.length - 1; i >= 0; i--) {
                output.write(this.dataCode[i]);
            }
        } else {
            if (this.oad != null && this.rsd != null && this.rcsd != null) {
                codeLength = 0;
                codeLength += this.rcsd.encode(output);
                codeLength += this.rsd.encode(output);
                codeLength += this.oad.encode(output);
            } else {
                throw new Exception("oad or rsd or rcsd is null");
            }
        }
        return codeLength;
    }

    public void encodeAndSave(int encodingSizeGuess) throws Exception {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = revOStream.toByteArray();
    }

    @Override
    public String toString() {
        if (this.oad != null && this.rsd != null && this.rcsd != null) {
            return "sequence: {" + "oad: " + this.oad + ", rsd: " + this.rsd + ", rcsd: " + this.rcsd + "}";
        } else {
            return "oad or rsd or rcsd is null";
        }
    }
}


